<template>
    <div style="position: relative">
        <div class="rx-input">
            <el-input
                    v-if="basicData.state != '已完成'"
                    @keydown.enter.native="carriageReturn($event)"
                    :id='"ipt" + indexIpt'
                    class="ipat"
                    type="textarea"
                    :key="indexIpt"
                    :autosize="{ minRows: 4, maxRows: 4}"
                    placeholder="请输入内容"
                    @focus="inputChange(indexIpt)"
                    v-model="content">
            </el-input>
            <ul class="list" :id='"list" + indexIpt'>
                <ol v-for="(item,index) in allMembers" :key="index" @click="chang(item)">{{item}}</ol>
            </ul>
        </div>
        <p></p>
        <div class="operation" v-if="basicData.state != '已完成'">
            <rx-upload ref="RxUpload"
                       class="rx-upload"
                       :action="action"
                       :size="size"
            ></rx-upload>

        </div>
        <div class="btn-save" v-if="basicData.state != '已完成'">
            <el-button type="primary" round size="mini" @click="clickReply">回复</el-button>
            <el-button type="info" v-show="isBtn" round size="mini" @click="close">取消</el-button>
        </div>
    </div>
</template>

<script>
    import RxUpload from "./RxUpload";
    import {taskinfo} from "../mixins/taskinfo";
    import {deepClone} from "../utils";

    export default {
        mixins: [taskinfo],
        name: "reply",
        components: {RxUpload},
        props: {
            isBtn: {
                type: Boolean,
                default: false,
            },
            size: {
                type: Number,
                default: 0,
            },
            basicData: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            indexIpt: {
                type: Number,
                default: 0,
            }
        },
        data() {
            return {
                content: "",
                action: '/seeyon/rest/attachment?applicationCategory=0&extensions=&firstSave=true',
                nameId: [],
                names: [],
                filterValue: '',
                allMembers: [],
                inputId: -2,
            }
        },
        computed: {},
        mounted() {
            this.loadNames();
            this.initAt();
           // this.loadKeyup();
        },
        watch: {},
        methods: {
            loadNames() {
                let arr = ['ALL']
                if (this.basicData.allMembers) {
                    let names = this.basicData.allMembers.split(',');
                    for (let i = 0; i < names.length; i++) {
                        arr.push(names[i]);
                    }
                }
                this.allMembers = arr;
            },

            chang(v) {
                this.content += v + ' ';
                document.getElementById('list' + this.indexIpt).style.display = 'none'
                if (this.basicData.allMemberIds) {
                    let ids = this.basicData.allMemberIds.split(',')
                    let names = this.basicData.allMembers.split(',');
                    if (v == 'ALL') {
                        for (let i = 0; i < ids.length; i++) {
                            this.nameId.push(ids[i]);
                        }
                    } else {
                        for (let i = 0; i < names.length; i++) {
                            if (names[i] == v) {
                                this.nameId.push(ids[i]);
                            }
                        }
                    }
                }
            },

            getFileList() {
                return this.$refs['RxUpload'].files;
            },

            clickReply() {
                this.nameId = this.unique(this.nameId)
                this.$emit('on-click-reply', this.content, this.nameId.toString());
                this.content = ''
                this.nameId = []
            },

            clearFiles() {
                this.$refs['RxUpload'].clearFiles();
            },
            //取消回复
            close() {
                this.$emit('on-close', false)
            },

            inputChange(index) {
                this.inputId = index
              //  console.log(index)
            },

            //初始@符号
            initAt() {
                let ipt = document.getElementById('ipt' + this.indexIpt);
                let list = document.getElementById('list' + this.indexIpt);

                let _this = this;

                ipt.oninput = function (e) {

                    //获取光标位置
                    var position = _this.getPosition(ipt);
                    ipt.value = ipt.value || '';
                    //如果光标后面是空格或没有内容,且光标前面最后一个是@
                    var s = ipt.value.charAt(position)
                    if ((s == "" || s == " ") && ipt.value.charAt(position - 1) == "@") {
                        var iStyle = window.getComputedStyle(ipt),
                            fz = parseFloat(iStyle.fontSize),//字体大小
                            wd = parseFloat(iStyle.width),//文本域宽度
                            lh = parseFloat(iStyle.lineHeight),//行高
                            pd = parseFloat(iStyle.paddingLeft),//左内边距

                            newStr = ipt.value.substr(0, position + 1),
                            //有换行符根据换行符拆分
                            valArr = newStr.indexOf("\n") !== -1 ? newStr.split("\n") : [ipt.value];
                        for (var i = 0, j = 0; i < valArr.length; i++) {
                            //把双字节的替换成两个单字节的然后再获得长度
                            var len = valArr[i].replace(/[^\x00-\xff]/g, "01").length / 2;
                            j += Math.ceil((len * fz) / wd);
                        }
                        let left = (len * fz) % wd == 0 ? wd : (len * fz) % wd + pd
                        list.style.left = left + "px"
                        list.style.top = j * lh + "px";
                        list.style.display = "block";
                    } else {
                        let className = document.getElementsByClassName("list")
                        for (let i = 0; i < className.length; i++) {
                            className[i].style.display = "none";
                        }
                    }
                }
            },
            //输入框获取光标
            getPosition(element) {
                var cursorPos = 0;
                if (document.selection) {//IE
                    var selectRange = document.selection.createRange();
                    selectRange.moveStart('character', -element.value.length);
                    cursorPos = selectRange.text.length;
                } else if (element.selectionStart || element.selectionStart == '0') {
                    cursorPos = element.selectionStart;
                }
                return cursorPos;
            },

            //键盘事件
            loadKeyup() {
                let _this = this;
                this.loadNames();
                //键盘按下事件
                let index = -1;
                document.getElementById('list' + _this.indexIpt).style.display = 'none';

                document.addEventListener("keyup", function (e) {
                    let lists = document.getElementsByTagName('ol');
                    var e = e || window.e;
                    _this.reset(lists);
                    _this.loadNames();
                    //向上键
                    if (e.keyCode == "38") {
                        index--
                        if (index >= 0) {
                            lists[index].className = 'active'
                        } else {
                            index = lists.length - 1;
                            lists[index].className = 'active'
                        }
                    }
                    //向下键
                    if (e.keyCode == "40") {
                        if (index < lists.length - 1) {
                            index++
                            lists[index].className = 'active'
                        } else {
                            index = 0
                            lists[index].className = 'active'
                        }
                    }
                    //enter确认键
                    if (e.keyCode == "13") {
                        if (_this.filterValue) {
                            document.getElementById('ipt' + _this.inputId).value = _this.content.replace(_this.filterValue, lists[index].innerHTML) + ' '
                        } else {
                            document.getElementById('ipt' + _this.inputId).value += lists[index].innerHTML + ' ';
                        }
                        document.getElementById('list' + _this.indexIpt).style.display = 'none';
                        return;
                    }

                    if (e.keyCode == '32') {
                        _this.allMembers = []
                    }

                    //输入搜索
                    if ((_this.content.lastIndexOf(' ') != -1
                        && _this.content.substring(_this.content.lastIndexOf(' ') + 1, _this.content.length).indexOf('@') != -1)
                        || _this.content.substring(_this.content.lastIndexOf('@') - 1, _this.content.lastIndexOf('@') == '')
                    ) {

                        let data = []
                        _this.filterValue = _this.content.substring(_this.content.lastIndexOf('@') + 1, _this.content.length)
                        let names = _this.basicData.allMembers.split(',');
                        if (_this.filterValue) {
                            _this.allMembers = []
                            names.forEach((d) => {
                                if (d == _this.filterValue) {
                                    data.push(d);
                                }
                            })
                            if (data.length > 0) {
                                _this.allMembers = data
                                if (e.keyCode != '32') {
                                    let list = document.getElementById('list' + _this.indexIpt);
                                    list.style.display = "block";
                                }
                            } else {
                                _this.allMembers.push('ALL')
                                if (e.keyCode != '32') {
                                    let list = document.getElementById('list' + _this.indexIpt);
                                    list.style.display = "block";
                                }
                            }
                        }
                    } else {
                        let list = document.getElementById('list' + _this.indexIpt);
                        list.style.display = "none";
                    }

                })
            },

            //重置class
            reset(lists) {
                for (let i = 0; i < lists.length; i++) {
                    lists[i].className = "";
                }
            },

            //数组去重
            unique(arr) {
                let hash = [];
                for (let i = 0; i < arr.length; i++) {
                    if (hash.indexOf(arr[i]) == -1) {
                        hash.push(arr[i]);
                    }
                }
                return hash;
            },
            carriageReturn(event) {
                let e = window.event || arguments[0];
                // console.log(e,e.keyCode)
                if (e.key == "Enter" || e.code == "Enter" || e.keyCode == 13) {
                    e.returnValue = false;
                    return false;
                }
            },
        }
    }
</script>

<style scoped>
    .operation {
        width: 60px;
        display: flex;
        justify-content: space-between;
    }

    .rx-input {
        width: calc(100% - 10px);
        height: 100%;
    }

    .btn-save {
        display: flex;
        justify-content: flex-end;
        margin-right: 10px;
        margin-bottom: 30px;
    }

    .rx-upload {
        margin-top: 5px;
    }

    #ipt {
        font-size: 16px;
        padding-left: 5px;
        line-height: 30px;
    }

    .list {
        margin: 5px 0;
        box-shadow: 0 2px 12px 0 #E4E7ED;
        border-radius: 4px;
        border: 1px solid #e4e7ed;
        box-sizing: border-box;
        background-color: #fff;
        position: absolute;
        list-style: none;
        overflow: hidden;
        overflow-y: scroll;
        max-height: 150px;
        width: 150px;
        overflow: auto;
        display: none;
        z-index: 100;
    }

    .list ol {
        height: 25px;
        line-height: 25px;
        padding-left: 5px;
    }

    .active {
        background: #efefef;
    }

    .list ol:hover {
        background: #efefef;
        cursor: pointer;
    }
</style>
